-- local function get_attacker()
-- 	local count = 6
-- 	while debug.getinfo(count) do
-- 		count = count + 1
-- 	end
-- 	count = count - 7
-- 	local temp = math.min(count, 22)
-- 	for i = 1, temp, 1 do
-- 		local index = 1
-- 		while true do
-- 			local name, value = debug.getlocal(5 + i, index)
-- 			if not name then
-- 				break
-- 			end
-- 			if
-- 				name == "inst" and value and type(value) == "table" and value.IsValid and type(value.IsValid) == "function" and
-- 					value:HasTag("player")
-- 			 then
-- 				return value
-- 			end
-- 			index = index + 1
-- 		end
-- 	end
-- end

local function OnHurted(inst, data)
	if data.newpercent < data.oldpercent then
		local self = inst.components.musha_exp_assigner
		if data.cause and data.afflicter and data.afflicter:HasTag("player") then
			self.damage[data.afflicter] = (self.damage[data.afflicter] or 0) + data.oldpercent - data.newpercent
			if data.oldpercent >= 0 and data.newpercent <= 0 then
				for k, v in pairs(self.damage) do
					if inst:IsNear(k, 20) then
						k:PushEvent("musha_gainexp", self.exp * self.damage[data.afflicter])
					end
				end
			end
		end
	end
end

local Musha_Exp_Assigner =
	Class(
	function(self, inst)
		self.inst = inst
		self.damage = {}
		if inst:HasTag("epic") then
			self.exp =
				inst.components.health.maxhealth * 0.01 +
				(inst.components.combat and inst.components.combat.defaultdamage * 0.3 or 0)
		else
			self.exp =
				inst.components.health.maxhealth * 0.003 +
				(inst.components.combat and inst.components.combat.defaultdamage * 0.02 or 0)
		end
		inst:ListenForEvent("healthdelta", OnHurted)
	end
)

function Musha_Exp_Assigner:OnSave()
	return self.damage
end

function Musha_Exp_Assigner:OnLoad(data)
	if data ~= nil then
		self.damage = data
	end
end

return Musha_Exp_Assigner
